//
//  ZXShopCartViewController.m
//  ZXShopCart
//
//  Created by Xiang on 16/2/2.
//  Copyright © 2016年 周想. All rights reserved.
//

#import "ZXShopCartViewController.h"
#import "GoodsModel.h"
#import "GoodsCategory.h"
#import "MJExtension.h"
#import "MenuItemCell.h"
#import "ShopCartView.h"
#import "ThrowLineTool.h"
#import "DetailListCell.h"
#import "AFNetworking.h"
#define ZXColor(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]

@interface ZXShopCartViewController ()<UITableViewDelegate, UITableViewDataSource, MenuItemCellDelegate, ThrowLineToolDelegate, DetailListCellDelegate>
{
    
}
@property (nonatomic, strong) UITableView   *leftTableView;
@property (nonatomic, strong) UITableView   *rightTableView;
@property (nonatomic, strong) NSArray       *dataArray;
@property (nonatomic, assign) BOOL          isRelate;
@property (nonatomic, strong) UIImageView   *redView;   //抛物线红点
@property (nonatomic, strong) ShopCartView  *shopCartView;
@property (nonatomic, assign) NSInteger     totalOrders;    //总数量
@property (nonatomic ,strong) NSMutableArray *detailArray;
@property (nonatomic ,strong) NSMutableArray *detailArray1;
@property (nonatomic ,strong) NSMutableArray *detailArray2;
@property (nonatomic ,strong) NSMutableArray *detailArray3;
@property (nonatomic ,strong) NSMutableArray *SequenceArray;
@property (nonatomic ,strong) NSMutableArray *titleArray;
@property (nonatomic ,strong) NSMutableArray *groupArr;
@end

@implementation ZXShopCartViewController

static NSString * const cellID = @"MenuItemCell";
static NSString * const ListCellID = @"DetailListCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"购物车";
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    CGRect viewBounds = self.view.bounds;
    float navBarHeight = self.navigationController.navigationBar.frame.size.height + 20;
    viewBounds.size.height = ([[UIScreen mainScreen] bounds].size.height) - navBarHeight;
    self.view.bounds = viewBounds;
    
    [self initData];
    
    [ThrowLineTool sharedTool].delegate = self;
    _isRelate = YES;
}

-(void)initData {
    _SequenceArray = [NSMutableArray arrayWithCapacity:0];
    if (!_dataArray) {
        _dataArray = [NSArray new];
        
        _detailArray = [NSMutableArray arrayWithCapacity:0];
        _detailArray1 = [NSMutableArray arrayWithCapacity:0];
        _detailArray2 = [NSMutableArray arrayWithCapacity:0];
        _detailArray3 = [NSMutableArray arrayWithCapacity:0];
        self.titleArray = [NSMutableArray arrayWithCapacity:0];
        NSString *urlString1 = @"http://api.nightnet.cn/api//Club/GetItemList?ClubID=0419026e-7e90-417e-b16f-b541e64d618a";
        AFHTTPSessionManager *manager1 = [AFHTTPSessionManager manager];
        manager1.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        [manager1 GET:urlString1 parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject1) {
            
            GoodsCategory *category = [[GoodsCategory alloc] init];
            for (NSMutableDictionary *dic in responseObject1) {
              GoodsModel *model = [GoodsModel mj_objectWithKeyValues:dic];
                NSString *SequenceStr = [NSString stringWithFormat:@"%d",model.Sequence];
                [_SequenceArray addObject:SequenceStr];
                [_titleArray addObject:model.ItemType];
                [_detailArray addObject:dic];
//                NSLog(@"_detailArray.count===%@",_detailArray);
                
            }
            _detailArray1 = [NSMutableArray new];
            [self groupSort];
//            NSMutableDictionary *categoryDic = [NSMutableDictionary new];
            
//            NSLog(@"_titleArray===%@",_titleArray);
            //去除多余元素
            NSMutableArray *listAry = [[NSMutableArray alloc]init];
            for (NSString *str in _SequenceArray) {
                if (![listAry containsObject:str]) {
                    [listAry addObject:str];
                }
            }
            NSMutableArray *listAry1 = [[NSMutableArray alloc]init];
            for (NSString *str in _titleArray) {
                if (![listAry1 containsObject:str]) {
                    [listAry1 addObject:str];
                }
            }
            _titleArray = listAry1;
            _SequenceArray = listAry;
            
            for (int i = 0; i<_titleArray.count; i++) {
                category.name = _titleArray[i];
                category.desciption = _titleArray[i];
                category.goodsArray = _groupArr[i];
                NSDictionary *stuDict = category.mj_keyValues;
                [_detailArray2 addObject:stuDict];
            }
//            NSLog(@"stuDict===%@",_detailArray2);
            _dataArray = [GoodsCategory objectArrayWithKeyValuesArray:_detailArray2];
            [self leftTableView];
            [self rightTableView];
            [self shopCartView];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error = %@", error);
        }];
        
    }
    
}

- (void)groupSort {
    // 1.定义一个测试的字典数组
    NSString *str;
    GoodsModel *model;
    NSMutableArray *dictArray = _detailArray;
    for (NSDictionary *dic in dictArray) {
        model = [GoodsModel mj_objectWithKeyValues:dic];
    };
    NSMutableArray *dictArr = [NSMutableArray array];
    for (int i = 0; i < dictArray.count; i++) {
        NSDictionary *dict = dictArray[i];
        [dictArr addObject:dict];
    }
    
    // 1、对数组按GroupTag排序
    
    NSArray *sortDesc = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Sequence" ascending:YES]];
    NSArray *sortedArr = [dictArr sortedArrayUsingDescriptors:sortDesc];
    // NSLog(@"排序后的数组:%@",sortedArr);
    // 2、对数组进行分组，按GroupTag
    // 遍历,创建组数组,组数组中的每一个元素是一个模型数组
    _groupArr = [NSMutableArray array];
    NSMutableArray *currentArr = [NSMutableArray array];
//    NSLog(@"class--%@",[currentArr class]);
    // 因为肯定有一个字典返回,先添加一个
    [currentArr addObject:sortedArr[0]];
    [_groupArr addObject:currentArr];
    // 如果不止一个,才要动画添加
    if(sortedArr.count > 1){
        for (int i = 1; i < sortedArr.count; i++) {
            // 先取出组数组中  上一个模型数组的第一个字典模型的groupID
            NSMutableArray *preModelArr = [_groupArr objectAtIndex:_groupArr.count-1];
            int preGroupID = [[[preModelArr objectAtIndex:0] objectForKey:@"Sequence"] intValue];
//            NSLog(@"preGroupID===%d",preGroupID);
            // 取出当前字典,根据groupID比较,如果相同则添加到同一个模型数组;如果不相同,说明不是同一个组的
            NSDictionary *currentDict = sortedArr[i];
            int groupID = [[currentDict objectForKey:@"Sequence"] intValue];
//            NSLog(@"groupID===%d",groupID);
            if (groupID == preGroupID) {
                [currentArr addObject:currentDict];
            }else{
                // 如果不相同,说明 有新的一组,那么创建一个模型数组,并添加到组数组_groupArr
                currentArr = [NSMutableArray array];
                [currentArr addObject:currentDict];
                [_groupArr addObject:currentArr];
            }
        }
    }
  
    // 3、遍历 对每一组 进行排序
    NSMutableArray *tempGroupArr = [NSMutableArray array];
    for (NSMutableArray *arr in _groupArr) {
//        NSArray *sortDesc = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Sequence" ascending:YES]];
        NSMutableArray *tempArr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            if([[obj1 objectForKey:@"Sequence"]intValue] < [[obj2 objectForKey:@"Sequence"]intValue]){
                return NSOrderedAscending;
            }
            if([[obj1 objectForKey:@"Sequence"]intValue] > [[obj2 objectForKey:@"Sequence"]intValue]){
                return NSOrderedDescending;
            }
            return NSOrderedSame;
        }];
        [tempGroupArr addObject:tempArr];
    }
    _groupArr = tempGroupArr;
    
}
/*
-(void)initData {
    if (!_dataArray) {
        _dataArray = [NSArray new];
 
        _detailArray = [NSMutableArray arrayWithCapacity:0];
        _detailArray1 = [NSMutableArray arrayWithCapacity:0];
        _detailArray2 = [NSMutableArray arrayWithCapacity:0];
        _detailArray3 = [NSMutableArray arrayWithCapacity:0];
        self.titleArray = [NSMutableArray arrayWithCapacity:0];
        NSString *urlString1 = @"http://api.nightnet.cn/api//Club/GetItemList?ClubID=0419026e-7e90-417e-b16f-b541e64d618a";
        AFHTTPSessionManager *manager1 = [AFHTTPSessionManager manager];
        manager1.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        [manager1 GET:urlString1 parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject1) {
            
            GoodsModel *listModel0;
            for (NSDictionary *dic0 in responseObject1) {
                listModel0 = [GoodsModel mj_objectWithKeyValues:dic0];
                //                [detailArray1 addObject:listModel2];
            }
            NSArray* arr2 = responseObject1;
            NSComparator finderSort = ^(id dic1,id dic2){
                NSString *string1 = dic1[@"Sequence"];
                NSString *string2 = dic2[@"Sequence"];
                if ([string1 integerValue] > [string2 integerValue]) {
                    return (NSComparisonResult)NSOrderedDescending;
                }else if ([string1 integerValue] < [string2 integerValue]){
                    return (NSComparisonResult)NSOrderedAscending;
                }
                else
                    return (NSComparisonResult)NSOrderedSame;
            };
            NSArray *resultArray2 = [arr2 sortedArrayUsingComparator:finderSort];
//            NSLog(@"resultArray===%@", resultArray2);
            for (NSMutableDictionary *dic in resultArray2) {
                [_detailArray addObject:dic];
            }
            NSMutableArray *_groupArr = [NSMutableArray array];
            NSMutableArray *currentArr = [NSMutableArray array];
//            NSLog(@"class--%@",[currentArr class]);
            // 因为肯定有一个字典返回,先添加一个
            [currentArr addObject:_detailArray[0]];
            [_groupArr addObject:currentArr];
            if (_detailArray.count > 1) {
                for (int i = 1; i<_detailArray.count; i++) {
                    // 先取出组数组中  上一个模型数组的第一个字典模型的groupID
                    NSMutableArray *preModelArr = [_groupArr objectAtIndex:_groupArr.count-1];
//                    NSLog(@"preModelArr===%@",preModelArr);
                    int preGroupID = [[[preModelArr objectAtIndex:0] objectForKey:@"Sequence"] intValue] ;
//                    NSLog(@"[preModelArr objectAtIndex:0]===%@",[_detailArray objectAtIndex:0][@"Sequence"]);
                    // 取出当前字典,根据Sequence比较,如果相同则添加到同一个模型数组;如果不相同,说明不是同一个组的
                    NSDictionary *currentDict = _detailArray[i];
                    int groupID = [[currentDict objectForKey:@"Sequence"] intValue];
                    //                int groupID = currentArr[@"Sequence"];
//                    NSLog(@"groupID==%d",groupID);
                    if (groupID == preGroupID) {
                        [currentArr addObject:currentDict];
                    }else{
                        // 如果不相同,说明 有新的一组,那么创建一个模型数组,并添加到组数组_groupArr
                        currentArr = [NSMutableArray array];
                        [currentArr addObject:currentDict];
                        [_groupArr addObject:currentArr];
//                        NSLog(@"_groupArr===%ld",_groupArr.count);
                    }
                }
//                NSLog(@"////////=====%@",_groupArr);
            }
            
            GoodsCategory *categorys = [[GoodsCategory alloc] init];
            for (NSMutableArray *arr in _groupArr) {
                categorys.goodsArray = arr;
//                NSLog(@"categorys.goodsArray==%@",categorys.goodsArray);
            }
            
            for (NSDictionary *dic in responseObject1) {
                GoodsModel *model1 = [GoodsModel mj_objectWithKeyValues:dic];
                [self.detailArray addObject:model1];
                [self.titleArray addObject:model1.ItemType];
                [categorys.goodsArray addObject:model1];
                //去除多余元素
                NSMutableArray *listAry = [[NSMutableArray alloc]init];
                for (NSString *str in _titleArray) {
                    if (![listAry containsObject:str]) {
                        [listAry addObject:str];
                    }
                }
                _titleArray = listAry;
//                NSLog(@"_titleArray==%@",_titleArray);
                for (NSString *itemType in _titleArray) {
                    categorys.name = itemType;
                    categorys.desciption = itemType;
                }
                NSMutableDictionary *statusDict = model1.mj_keyValues;
//                NSLog(@"statusDict===%@",statusDict);
//                [_detailArray addObject:statusDict];
//                NSLog(@"_detailArray===%lu",(unsigned long)_detailArray.count);
//                NSMutableDictionary *dic1 = [NSMutableDictionary new];
//                [dic1 setValue:categorys.name forKey:@"name"];
//                NSMutableDictionary *dic2 = [NSMutableDictionary new];
//                [dic2 setValue:categorys.desciption forKey:@"desciption"];
//                NSMutableDictionary *dic3 = [NSMutableDictionary new];
//                [dic3 setValue:categorys.goodsArray forKey:@"goods"];
//                [_detailArray1 addObject:dic1];
//                [_detailArray2 addObject:dic2];
//                [_detailArray3 addObject:dic3];
////                NSLog(@"_detailArray1=%ld", _detailArray1.count);
//                NSDictionary *stuDict = categorys.mj_keyValues;
//                //            NSLog(@"stuDict====%@", stuDict);
//                [_detailArray addObject:stuDict];
            }
//            NSLog(@"_detailArray===%lu",_detailArray.count);
                 NSError *error = nil;
                NSArray *arr = _detailArray1;
                
                _dataArray = [GoodsCategory objectArrayWithKeyValuesArray:arr];
//            NSLog(@"_dataArray.count==%@",_dataArray);
            NSDictionary *di  = categorys.mj_keyValues;
            NSLog(@"di===%@",di);
                if (error) {
                    NSLog(@"address.json - fail: %@", error.description);
                }
            [self leftTableView];
            [self rightTableView];
            [self shopCartView];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error = %@", error);
        }];
        
    }

}
 */

- (NSMutableArray *)orderArray {
    if (!_orderArray) {
        _orderArray = [NSMutableArray array];
    }
    return _orderArray;
}

- (UITableView *)leftTableView {
    if (nil == _leftTableView) {
        _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width * 0.25, self.view.frame.size.height - 50)];
        _leftTableView.backgroundColor = [UIColor whiteColor];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_leftTableView];
    }
    return _leftTableView;
    
}

- (UITableView *)rightTableView {
    if (nil == _rightTableView) {
        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 0.25, 0, self.view.frame.size.width * 0.75, self.view.frame.size.height - 50)];
        _rightTableView.backgroundColor = [UIColor whiteColor];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        //_rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        [_rightTableView registerNib:[UINib nibWithNibName:NSStringFromClass([MenuItemCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_rightTableView];
    }
    return _rightTableView;
}

- (ShopCartView *)shopCartView {
    if (!_shopCartView) {
        _shopCartView = [[ShopCartView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 50, CGRectGetWidth(self.view.bounds), 50) inView:self.view];
        [self.view addSubview:_shopCartView];
        //_shopCartView.orderArray = [NSMutableArray new];
        _shopCartView.detailListView.listTableView.delegate = self;
        _shopCartView.detailListView.listTableView.dataSource = self;
        [_shopCartView.detailListView.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([DetailListCell class]) bundle:nil] forCellReuseIdentifier:ListCellID];
    }
    return _shopCartView;
}

- (UIImageView *)redView {
    if (!_redView) {
        _redView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        _redView.image = [UIImage imageNamed:@"adddetail"];
        _redView.layer.cornerRadius = 10;
    }
    return _redView;
}
#pragma mark dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == _leftTableView) {
        return 1;
    } else if (tableView == _rightTableView) {
        return _dataArray.count;
    } else {
        return 1;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //该项目的demo就是数组里面装着很多字典，字典里面又有数组
    //NSDictionary *item = [_dataArray objectAtIndex:section];
    GoodsCategory *goodsCategory = _dataArray[section];
    if (tableView == _leftTableView) {
        return _dataArray.count;
    } else if (tableView == _rightTableView) {
        //return [[item objectForKey:@"goodsArray"] count];
        return goodsCategory.goodsArray.count;
    } else {
        return _orderArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTableView) {
        static NSString *CellIdentifier = @"Cell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            cell.backgroundColor = ZXColor(240, 240, 240);
            UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
            selectedBackgroundView.backgroundColor = [UIColor whiteColor];
            cell.selectedBackgroundView = selectedBackgroundView;
            
            // 左侧示意条
            UIView *liner = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 6, 40)];
            liner.backgroundColor = [UIColor orangeColor];
            [selectedBackgroundView addSubview:liner];
        }
        
        GoodsCategory *goodsCategory = _dataArray[indexPath.row];
        cell.textLabel.text = goodsCategory.goodsCategoryName;
        
        return cell;
    } else if (tableView == _rightTableView) {
        
        MenuItemCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[MenuItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        cell.delegate = self;
        
        GoodsCategory *goodsCategory = _dataArray[indexPath.section];
        GoodsModel *goods = goodsCategory.goodsArray[indexPath.row];
        
        cell.goods = goods;
        
        return cell;
    } else if (tableView == _shopCartView.detailListView.listTableView) {
        DetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:ListCellID];
        cell.delegate = self;
        GoodsModel *goods = [_orderArray objectAtIndex:indexPath.row];
        cell.goods = goods;
        
        return cell;
    } else {
        return nil;
    }
}

#pragma mark delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _leftTableView) {
        return 40;
    } else if (tableView == _rightTableView) {
        return 50;
    } else {
        return 50;
    }
}

//返回每一个组头的高度，如果想达到有那种效果则一定要做这个操作
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == _rightTableView) {
        return 30;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (tableView == _rightTableView) {
        return 0.01;
    } else {
        return 0;
    }
}

//返回组头部的那块View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == _rightTableView) {
        UIView *view = [[UIView alloc]init];
        view.frame = CGRectMake(0, 0, tableView.frame.size.width, 30);
        view.backgroundColor = ZXColor(240, 240, 240);
        [view setAlpha:0.7];
        UILabel *label = [[UILabel alloc]initWithFrame:view.bounds];
        GoodsCategory *goodsCategory = [_dataArray objectAtIndex:section];
        NSString *title = _titleArray[section];
        [label setText:[NSString stringWithFormat:@"  %@",title]];
        [view addSubview:label];
        return view;
    } else {
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //左边tableView
    if (tableView == _leftTableView) {
        _isRelate = NO;
        [self.leftTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
        
        //点击了左边的cell，让右边的tableView跟着滚动
        [self.rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.row] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    } else if (tableView == _rightTableView) {
        [_rightTableView deselectRowAtIndexPath:indexPath animated:NO];
        
        NSLog(@"点击这里可以跳到详情页面");
    } else {
        [_shopCartView.detailListView.listTableView deselectRowAtIndexPath:indexPath animated:NO];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if (_isRelate) {
        NSInteger topCellSection = [[[tableView indexPathsForVisibleRows] firstObject] section];
        if (tableView == _rightTableView) {
            [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:topCellSection inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingFooterView:(UIView *)view forSection:(NSInteger)section {
    if (_isRelate) {
        NSInteger topCellSection = [[[tableView indexPathsForVisibleRows] firstObject] section];
        if (tableView == _rightTableView) {
            [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:topCellSection inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }
}

#pragma mark - UISCrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    _isRelate = YES;
}

#pragma mark - MenuItemCellDelegate
- (void)menuItemCellDidClickMinusButton:(MenuItemCell *)itemCell {
    // 计算总价
    _totalPrice = _totalPrice - itemCell.goods.goodsSalePrice;
    
    // 设置总价
    [_shopCartView setTotalPrice:_totalPrice];
    
    --self.totalOrders;
    _shopCartView.badgeValue = self.totalOrders;
    
    
    // 将商品从购物车中移除
    if (itemCell.goods.orderCount == 0) {
        [self.orderArray removeObject:itemCell.goods];
    }
    [_shopCartView.detailListView.listTableView reloadData];
    _shopCartView.detailListView.objects = _orderArray;
    _shopCartView.orderArray = _orderArray;
}

- (void)menuItemCellDidClickPlusButton:(MenuItemCell *)itemCell {
    // 计算总价
    _totalPrice = _totalPrice + itemCell.goods.goodsSalePrice;
    // 设置总价
    [_shopCartView setTotalPrice:_totalPrice];
    
    //通过坐标转换得到抛物线的起点和终点
    CGRect parentRectA = [itemCell convertRect:itemCell.plusButton.frame toView:self.view];
    CGRect parentRectB = [_shopCartView convertRect:_shopCartView.shopCartBtn.frame toView:self.view];
    [self.view addSubview:self.redView];
    [[ThrowLineTool sharedTool] throwObject:self.redView from:parentRectA.origin to:parentRectB.origin];
    ++self.totalOrders;
    _shopCartView.badgeValue = self.totalOrders;
    
    
    // 如果这个商品已经在购物车中，就不用再添加
    if ([self.orderArray containsObject:itemCell.goods]) {
        [_shopCartView.detailListView.listTableView reloadData];
    } else {
        // 添加需要购买的商品
        [self.orderArray addObject:itemCell.goods];
        [_shopCartView.detailListView.listTableView reloadData];
    }
    _shopCartView.detailListView.objects = _orderArray;
    _shopCartView.orderArray = _orderArray;
}

#pragma mark - ThrowLineToolDelegate
- (void)animationDidFinish {
    
    [self.redView removeFromSuperview];
    [UIView animateWithDuration:0.1 animations:^{
        _shopCartView.shopCartBtn.transform = CGAffineTransformMakeScale(0.8, 0.8);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            _shopCartView.shopCartBtn.transform = CGAffineTransformMakeScale(1, 1);
        } completion:^(BOOL finished) {
            
        }];
        
    }];
}

#pragma mark - DetailListCellDelegate
- (void)orderDetailCellPlusButtonClicked:(DetailListCell *)cell {
    NSLog(@"订单 + 按钮点击: %@ %@ %i", cell.goods.goodsID, cell.goods.goodsName, cell.goods.goodsStock);
    // 计算总价
    _totalPrice = _totalPrice + cell.goods.goodsSalePrice;
    // 设置总价
    [_shopCartView setTotalPrice:_totalPrice];
    ++self.totalOrders;
    _shopCartView.badgeValue = self.totalOrders;
    
    _shopCartView.detailListView.objects = _orderArray;
    _shopCartView.orderArray = _orderArray;
    [_shopCartView updateFrame:_shopCartView.detailListView];
    [_shopCartView.detailListView.listTableView reloadData];
    [_rightTableView reloadData];
}

- (void)orderDetailCellMinusButtonClicked:(DetailListCell *)cell {
    NSLog(@"订单 - 按钮点击: %@ %@ %i", cell.goods.goodsID, cell.goods.goodsName, cell.goods.goodsStock);
    // 计算总价
    _totalPrice = _totalPrice - cell.goods.goodsSalePrice;
    // 设置总价
    [_shopCartView setTotalPrice:_totalPrice];
    --self.totalOrders;
    _shopCartView.badgeValue = self.totalOrders;
    
    // 将商品从购物车中移除
    if (cell.goods.orderCount == 0) {
        [self.orderArray removeObject:cell.goods];
    }
    _shopCartView.detailListView.objects = _orderArray;
    _shopCartView.orderArray = _orderArray;
    [_shopCartView updateFrame:_shopCartView.detailListView];
    [_shopCartView.detailListView.listTableView reloadData];
    [_rightTableView reloadData];
}

@end
